package com.ruoyi.common.utils.oss;

import com.aliyun.oss.*;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * 阿里云oss工具类
 *
 * @author xqs
 */
@Component
public class AliyunOSSUtil {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);

    @Value("${oss.endpoint}")
    private String endPoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.pathPrefix}")
    private String pathPrefix;

    @Value("${oss.domainName}")
    private String domainName;



    /**
     * 上传文件。
     */
    public AjaxResult upLoad(MultipartFile file) {
        logger.info("------OSS文件上传开始--------" + file.getName());
        AjaxResult ajaxResult = AjaxResult.success();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        try {
            // 判断容器是否存在,不存在就创建
            if (!ossClient.doesBucketExist(bucketName)) {
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }

            // 设置文件路径和名称
            String dateStr = DateUtils.getDate();
            String fileName= UUID.randomUUID().toString().replace("-", "") + "-" + file.getOriginalFilename();
            String fileUrl = pathPrefix+"/"+dateStr + "/" + fileName;

            File f = null;
            try {
                f = File.createTempFile("tmp", null);
                file.transferTo(f);
                f.deleteOnExit();
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 上传文件
//            PutObjectResult result = ossClient.putObject(new PutObjectRequest(aliOssConfig.getBucketName(), fileUrl,f)
//                    .withProgressListener(new FileProgressListener()));
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl,f));
            // 设置权限(公开读)
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if (result != null) {
                logger.info("------OSS文件上传成功------" + fileUrl);
            }
            ajaxResult.put("url",domainName+"/"+fileUrl);
            ajaxResult.put("fileName", fileUrl);
            ajaxResult.put("newFileName", fileName);
            ajaxResult.put("originalFilename", file.getOriginalFilename());
            return ajaxResult;
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
            throw new ServiceException("文件上传失败");
        } catch (ClientException ce) {
            logger.error(ce.getErrorMessage());
            throw new ServiceException("文件上传失败");
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceException("文件上传失败");
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }



    public String uploadByFile(File file){
        logger.info("------OSS文件上传开始--------" + file.getName());
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        try {
            // 判断容器是否存在,不存在就创建
            if (!ossClient.doesBucketExist(bucketName)) {
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }

            // 设置文件路径和名称
            String dateStr = DateUtils.getDate();
            String fileName= UUID.randomUUID().toString().replace("-", "") + "-" + file.getName();
            String fileUrl = pathPrefix+"/"+dateStr + "/" + fileName;

            // 上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl,file));
            // 设置权限(公开读)
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if (result != null) {
                logger.info("------OSS文件上传成功------" + fileUrl);
            }
            return domainName+"/"+fileUrl;
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
            throw new ServiceException("文件上传失败");
        } catch (ClientException ce) {
            logger.error(ce.getErrorMessage());
            throw new ServiceException("文件上传失败");
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceException("文件上传失败");
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

}
